package com.lenovo.lcdmoauth.config;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import java.util.List;

public class CustomRevocationAuthenticationConverter implements AuthenticationConverter {

    public CustomRevocationAuthenticationConverter() {
    }

    @Override
    public Authentication convert(HttpServletRequest request) {
        Authentication clientPrincipal = SecurityContextHolder.getContext().getAuthentication();
        MultiValueMap<String, String> parameters = SecurityUtils.getParameters(request);
        String itcode = (String) parameters.getFirst("itcode");
        if (!StringUtils.hasText(itcode) || ((List) parameters.get("itcode")).size() != 1) {
            throwError("invalid_request", "itcode");
        }
        return new CustomRevocationAuthenticationToken(itcode, clientPrincipal);
    }

    private static void throwError(String errorCode, String parameterName) {
        OAuth2Error error = new OAuth2Error(errorCode, "OAuth 2.0 Token Revocation Parameter: " + parameterName, "https://datatracker.ietf.org/doc/html/rfc7009#section-2.1");
        throw new OAuth2AuthenticationException(error);
    }
}
